package com.lun.swordtowardoffer2.c05;

import java.util.HashMap;
import java.util.Map;

public class IsAnagram {

	//针对26英文字母
	public boolean isAnagram(String str1, String str2) {
		
		if(str1.length() != str2.length() || str1.equals(str2))
			return false;
		
		int[] counts = new int[26];
		
		for(char ch : str1.toCharArray()) {
			counts[ch - 'a']++;
		}
		
		for(char ch : str2.toCharArray()) {
			if(counts[ch - 'a'] == 0) return false;
			counts[ch - 'a']--;
		}
		return true;
	}
	
	//针对大多数字符
	public boolean isAnagram2(String str1, String str2) {
		if(str1.length() != str2.length() || str1.equals(str2))
			return false;
		
		Map<Character, Integer> counts = new HashMap<>();
		
		for(char ch : str1.toCharArray()) {
			counts.put(ch, counts.getOrDefault(ch, 0) + 1);
		}
		
		for(char ch : str2.toCharArray()){
			if(!counts.containsKey(ch) || counts.get(ch) == 0) {
				return false;
			}
			counts.put(ch, counts.get(ch) - 1);
		}
		
		return true;
	}
	
}
